import { defineStore } from "pinia";
import { asyncRoutes, constantRoutes, routerArray, notFoundRouter } from "@/routers/index.ts";
import { hasPermission, filterAsyncRoutes } from "@/utils/routers";
import { filterKeepAlive, filterRoutes } from "@/utils/routers";
import { reqGetRouter } from "@/api/user/index.ts";
import { RouteRecordRaw, useRouter } from "vue-router";
import { hasPermiOr, hasRole } from "@/store/modules/auth";
import Layout from "@/layout/index.vue";

export const usePermissionStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: "permissionState",
  // state: 返回对象的函数
  state: () => ({
    // 路由
    routes: [],
    // 动态路由
    addRoutes: [],
    // 缓存路由
    cacheRoutes: {},
    // 查询路由
    checkRouter: [],
    // 是否已经有查询路由了
    hasCheckRouter: false
  }),
  getters: {
    permission_routes: (state) => {
      return state.routes;
    },
    // 要进行缓存的路由
    keepAliveRoutes: (state) => {
      return filterKeepAlive(asyncRoutes);
    }
  },
  // 可以同步 也可以异步
  actions: {
    // 生成路由
    generateRoutes(roles) {
      return new Promise(async (resolve) => {
        // 在这判断是否有权限，哪些角色拥有哪些权限
        let accessedRoutes;
        console.log("===================================================11======================");
        console.log(asyncRoutes);
        console.log(roles);
        /*if (roles && roles.length && !roles.includes("admin")) {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);/!*根据角色来过滤路由权限*!/
        } else {
          accessedRoutes = asyncRoutes || [];
        }*/
        accessedRoutes = asyncRoutes || [];
        console.log("=========================================================================");
        console.log(accessedRoutes);
        console.log(notFoundRouter);
        console.log("=========================================================================");


          /*获取查询路由*/
          await reqGetRouter().then((result) => {
            if (result.code === 200) {
              /*将data存到menuList中*/
              //将原始数据进行深拷贝，防止修改原始数据
              const sdata = JSON.parse(JSON.stringify(result.data));
              const rdata = JSON.parse(JSON.stringify(result.data));

              console.log("=-==-=");
              console.log(result.data);
              /*生成需要添加的路由表的路由*/
              const lastRouterRouters = filterAsyncRouter(sdata); /*获取的是动态路由信息*/
              //console.log("lastRouterRouters", lastRouterRouters);
              /*生成菜单中要使用的路由*/
              const lastRouterMenu = filterAsyncRouter(rdata, false, true); /*获取的数路由的菜单信息*/
              const router = useRouter();
              console.log("lastRouterMenu", lastRouterMenu);
              //对动态路由进行过滤
              //const asyncRoutes = filterDynamicRoutes(asnycRouters)
             /* lastRouterRouters.forEach((item) => {
                accessedRoutes = accessedRoutes.concat(item)
              })*/
              lastRouterMenu.forEach((item) => {
                accessedRoutes = accessedRoutes.concat(item)
              })

              this.hasCheckRouter = true;
              //console.log(lastRouterMenu[5]);
            }
          });

        accessedRoutes = accessedRoutes.concat(notFoundRouter);
        this.routes = constantRoutes.concat(accessedRoutes);
        console.log('要添加的路由');
        console.log(this.routes);
        this.addRoutes = accessedRoutes;
        resolve(accessedRoutes);
      });
    },
    // 清除路由
    clearRoutes() {
      this.routes = [];
      this.addRoutes = [];
      this.cacheRoutes = [];
    },
    // 获取缓存路由信息
    getCacheRoutes() {
      this.cacheRoutes = filterKeepAlive(asyncRoutes);
      return this.cacheRoutes;
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////


  }
});


import Layout from "@/layout/index.vue";
import ParentView from '@/components/ParentView/index.vue'

const modules = import.meta.glob("../../views/**/*.vue"); /*获取所有的.vue组件*/

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(
  asyncRouterMap: any[],
  lastRouter = false,
  type = false
) {
  return asyncRouterMap.filter((route) => {
    if (type && route.children) {
      /*对path的拼接*/
      route.children = filterChildren(route.children, route);
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      console.log("--------------------");
      if (route.component === "Layout") {
        route.component = () => import("@/layout/index.vue");
      } else if (route.component === "ParentView") {
        console.log('修改前', route.component);
        route.component = route.path + '/index'
        console.log('修改后', route.component);
        console.log('ParentView');
        if (modules[`../../views/${route.component}.vue`] != null) {
          route.component = modules[`../../views/${route.component}.vue`];
        }
        route.component = () => import("@/components/ParentView/index.vue");
      } else if (route.component === "InnerLink") {
        route.component = () => import("@/layout/components/InnerLink/index.vue");
      } else {
        if (modules[`../../views/${route.component}.vue`] != null) {
          route.component = modules[`../../views/${route.component}.vue`];
        }
      }
      console.log('============================');
      console.log(route.component);
    }

    /*该路由有孩子*/
    if (route.children != null && route.children && route.children.length) {
      route.redirect = route.children[0].path
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      delete route["redirect"];
    }
    return route;
  });
}

/*对孩子的path进行拼接*/
function filterChildren(
  childrenMap: any[],
  lastRouter = false
): RouteRecordRaw[] {
  let children: any[] = []; /*用老记录孩子的路由信息，最后进行返回*/
  childrenMap.forEach((el, index: number) => {
    /*如果该元素有孩子并且孩子超过一个*/
    if (el.children && el.children.length) {
      /*该元素的commponent为ParentView没有lastRouter*/
      if (el.component === "ParentView" && !lastRouter) {
        /*ParentView表示的是该组件的元素的位置*/
        /*遍历该元素的孩子的孩子，对其进行路由拼接*/
        el.children.forEach((c: any) => {
          c.path = el.path + "/" + c.path;
          if (c.children && c.children.length) {
            children = children.concat(filterChildren(c.children, c));
            return;
          }
          children.push(c);
        });
        return;
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + "/" + el.path;
    }
    children = children.concat(el);
  });
  return children;
}

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes: any[]) {
  const res: any[] = [];
  routes.forEach((route) => {
    console.log("-----------------------------0");
    console.log(route.permissions);
    if (route.permissions) {
      if (hasPermiOr(route.permissions)) {
        res.push(route);
      }
    } else if (route.roles) {
      if (hasRole(route.roles)) {
        res.push(route);
      }
    }
  });
  return res;
}

/*const loadView = (view: string) => () => import(`@/views/${view}.vue`)*/

export const loadView = (view: string) => {
  return () => import(`@/views/${view}.vue`);
  /*if (import.meta.env.DEV) {
            return () => import(`@/views/${view}.vue`)
        } else {
            // 使用 import 实现生产环境的路由懒加载
            return () => import(`@/views/${view}.vue`)
        }*/
};
